package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * @author bairimengchang
 * @version 1.0
 * @project sky-take-out
 * @description 对插入和修改sql执行前，为创建时间/创建人/修改时间/修改人进行统一赋值，拦截mapper包以及被注解包裹的
 * @date 2024/08/06 09:27:11
 */
@Component
@Aspect
@Slf4j
public class AutoFillAspect {

    //切点，拦截mapper包以及被AutoFill注解包裹的
    @Pointcut(value = "execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void pointCut() {
    }

    //前置通知
    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        log.info("公共字段填充切面前置通知调用中");

        //拿到注解的value参数
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType operationType = autoFill.value();

        //拿方法参数，这里约定取第一个参数作为实体对象进行赋值
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }

        Object entity = args[0];

        //准备数据
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        log.info("当前实体对象:{}, 当前登录人:{}", entity, currentId);

        if (operationType == OperationType.INSERT) {
            //执行插入操作（需要设置创建时间和创建人id）
            try {
                Method setCreateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setCreateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);

                //通过反射赋值
                setCreateTime.invoke(entity, now);
                setCreateUser.invoke(entity, currentId);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        if (operationType == OperationType.UPDATE) {
            //执行更新操作（需要设置修改时间和修改人）
            try {
                Method setUpdateTime = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                setUpdateTime.invoke(entity, now);
                setUpdateUser.invoke(entity, currentId);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        log.info("切面方法调用完毕");
    }

}
